import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from './store'
import { asyncRouter } from './router'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userid) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRouter = asyncRouter.filter(item => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRouter', filterRouter)
        router.addRoutes([...filterRouter, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)//
      } else {
        next()// 放过
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
